package com.example.grpc.proxy;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.http2.*;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.BlockingQueue;

@Slf4j
public class CustHttp2ClientInit extends ChannelInitializer<SocketChannel> {

    private final Http2HeadersFrame http2HeadersFrame;
    private final Http2DataFrame dataFrame;
    private final ChannelHandlerContext outboundContext;

    public CustHttp2ClientInit(Http2HeadersFrame http2HeadersFrame, Http2DataFrame dataFrame, ChannelHandlerContext outboundContext) {
        this.http2HeadersFrame = http2HeadersFrame;
        this.dataFrame = dataFrame;
        this.outboundContext = outboundContext;
    }

    @Override
    protected void initChannel(SocketChannel channel) throws Exception {
        Http2FrameCodec http2FrameCodec = Http2FrameCodecBuilder.forClient().build();
        channel.pipeline().addLast(http2FrameCodec);
        channel.pipeline().addLast(new LoggingHandler(LogLevel.DEBUG));
        channel.pipeline().addLast(new GrpcClientHandler(http2HeadersFrame, dataFrame, outboundContext));
        channel.pipeline().addLast(new Http2MultiplexHandler(new ChannelInboundHandlerAdapter()));
    }
}
